/**
 * Javascript file for sources needed at report_archive.php
 */

var grid_layout_done = false;
var delete_box_done = new Array();

//Load the Visualization API
google.load("visualization", "1", {'packages':['corechart','annotatedtimeline']});

function galaxytool_drawChart() {
	// annotatedtimeline or line chart
	var isLineChart = dijit.byId("chart_type").get("value") == "linechart";
	
	var items = grid1.selection.getSelected();
	if (items.length == 0) return;
	
	var selected_for_display = new Array();
	var scantime = grid1.getItem(2);

	var entities = new Array();
	var attributes = grid1.store.getAttributes(scantime);
			
	entities.push(grid1.store.getValues(scantime, "c0"));
	for(var j=attributes.length-1; j>0; j--) {
		// ignore attributes which are not c\d+
		var result = attributes[j].replace(/c\d+/, "");
		if (result == "") {
			var value = grid1.store.getValue(scantime, attributes[j]);
			entities.push(value);
		}
	}
	selected_for_display.push(entities);

	for(var i=0; i<items.length; i++) {
		var entities = new Array();
		selectedItem = items[i];
		
		// remove selected rows for "fleet", "buildings" etc
		var key = store1.getValue(selectedItem, "key");
		if (key == "msg_id" || key == "details" || key == "scantime" || 
			key == "h1" || key == "h2" || key == "h3" || key == "h4" || key == "h5") {
			continue;
		}
		
		var attributes = grid1.store.getAttributes(selectedItem);
		 
		var value = grid1.store.getValue(selectedItem, "c0");
		entities.push(value);
		for(var j=attributes.length-1; j>0; j--) {
			// ignore attributes which are not c\d+
			var result = attributes[j].replace(/c\d+/, "");
			if (result == "") {
				var value = grid1.store.getValue(selectedItem, attributes[j]);
				if (j == 0) {
					entities.push(value);
				} else {
					entities.push(parseInt(value));
				}	
			}
		}
		selected_for_display.push(entities);
	}
	
	if (selected_for_display.length < 2) {
		return;
	}
	
	var data = new google.visualization.DataTable();
	for (var i=0; i<selected_for_display.length; i++) {
		switch(i) {
			case 0:
				data.addColumn('datetime', selected_for_display[i][0]);
				break;
			
			default:
				data.addColumn('number', selected_for_display[i][0]);
				break;
		}
	}
	
	data.addRows(selected_for_display[0].length - 1);

	for (var j=1; j<selected_for_display[0].length; j++) { // number of columns
		for (var i=0; i<selected_for_display.length; i++) { // number of selected lines + scantime (always selected)
			switch(i) {
				case 0:
					var date = selected_for_display[i][j].toString().replace(/\-/g, " ").replace(/\:/g, " ").split(" ");
					if (date.length != 6) console.log("invalid date format provided");
					data.setValue(j-1, i, new Date(
							parseInt(date[0],10), 
							parseInt(date[1],10)-1 ,
							parseInt(date[2],10), 
							parseInt(date[3],10),
							parseInt(date[4],10), 
							parseInt(date[5],10))
					);
					break;
				
				default:
					data.setValue(j-1, i, selected_for_display[i][j]);
					if (isLineChart)
						data.setFormattedValue(j-1, i, NumberFormat(selected_for_display[i][j]));
					break;
			}
		}
	}
	
	if (isLineChart) {		
		var formatter = new google.visualization.DateFormat({pattern: 'yyyy-MM-dd HH:mm:ss'});
		formatter.format(data,0);
		var dialog = dijit.byId("ChartDialog");
		dialog.set("content", '<div id="chart_div"></div>');
		var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
		var options = {
				backgroundColor: '#13181D',
	            vAxis: {maxValue: 10, textStyle: { color: '#C4C4C4' } },
	            hAxis: {maxValue: 10, textStyle: { color: '#C4C4C4' }, gridlines: { color: '#13181D' } },
	            legend: {textStyle: { color: '#C4C4C4'}},
				width: 700, 
				height: 400,
				pointSize: 5
			}
		chart.draw(data, options);
		dialog.show();
		
	} else {
		var dialog = dijit.byId("ChartDialog");
		dialog.set("content", '<div id="chart_div" style="width: 1000px; height: 500px;"></div>');
		// the dialog has to be shown before (!) the chart is drawn, otherwise we will get an exception, saying that width is 0
		dialog.show();	
		var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
		chart.draw(data, {displayAnnotations: true, dateFormat: 'yyyy-MM-dd HH:mm:ss', thickness: 2, legendPosition: 'newRow'});
	}
}

function galaxytool_archive_delete() {
	var confirmed = confirm(archive_confirm_delete);
	if (confirmed != true) return;
	
	var columns = 0;
	var column_name = "";
	var to_be_deleted = new Array();
	do  {
		columns++;
		column_name = "c"+columns;
		var msg_id = store1.getValue(grid1.getItem(0), column_name);
		
		if (typeof msg_id!='undefined') {
			if (dijit.byId(msg_id).get("checked") == true) {
				to_be_deleted.push(msg_id);
			}
		}
		
	} while ((typeof msg_id != "undefined") && msg_id != "" && columns < 200);

	// create ajax request to delete reports
	var source_url = "ajax/ajax_report_archive.php?type=delete";
	var xhrArgs = {
	        url: source_url,
	        content : {
	        	"msg_id" : to_be_deleted.toString()
	    		},
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		// request reload store content and re-create grid
					var old_url = store1.url;
					store1.close();
					store1 = new dojo.data.ItemFileReadStore({url: old_url});
					grid_layout_done = false;
					grid1.setStore(store1);
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
	
}


function galaxytool_show_report(msg_id) {
	var columns		 = 0;
	var column_name	 = "";
	var selected_column = "";
	do  {
		columns++;
		column_name = "c"+columns;
		var column_message_id = store1.getValue(grid1.getItem(1), column_name); // start with c1
		if (column_message_id == msg_id) {
			selected_column = column_name;
			break;
		}
	}  while (selected_column == "" && columns < 200);
	if (selected_column == "") return;
	
	// collect all report information of that column into one array
	try {
		var row  = 0;
		var key  = "";
		var text = "";
		var reportInfo = new Object();
		do  {
			key   = store1.getValue(grid1.getItem(row), "key");
			value = store1.getValue(grid1.getItem(row), selected_column);
			var text = store1.getValue(grid1.getItem(row), "c0");
			
			if (key == "metal" || key == "crystal" || key == "deuterium" || key == "energy") text +=":"; // resources must have : for simulations
			reportInfo[key] = new Array(2);
			reportInfo[key][0] = value;
			reportInfo[key][1] = text;

			row++;
		}  while (row < 200);
	} catch(no_more_items) { }
	
	var dialog = dijit.byId("ReportDialog");
	var content = galaxytool.report_display.display(resources_on_text, "", report_coordinates, "", report_when, "", "", reportInfo, galaxytool_is_moon, false, "", galaxytool_total_res_text);
	dialog.set("content", content);
	dialog.show();
	galaxytool.report_display.addReportClickAndCloseListener();
}

// formatter for column 0
function galaxytool_archive_formatter(val, rowIdx, cell) {
	var key = store1.getValue(grid1.getItem(rowIdx), "key");
	
	if (key == "msg_id" || key == "h1" || key == "h2" || key == "h3" || key == "h4" || key == "h5") {
		cell.customClasses.push("public");
		if (key != "msg_id") {
			val = '<div style="height:16px;">'+val+'</div>';
		}
	}
	
	if (key == "details") {
		val = '<div style="height:16px;"></div>';
	}
	
	if (key == "res_sum" || key == "fleet_sum" || key == "def_sum") {
		val = "&sum; " + val;
		cell.customClasses.push("sum_row");
	}
	
	return val;
}

function galaxytool_archive_formatter2(val, rowIdx, cell) {
	cell.customClasses.push("centered_text");
	
	if (rowIdx == 0) {
		if (galaxytool_delete == false) return "";
		
		// create checkbox for each cell only once
		if (delete_box_done[val] == true) {
			return dijit.byId(val);
		}
		delete_box_done[val] = true;
		try {
			var checkBox = new dijit.form.CheckBox({
				id: val,
				name: "checkBox",
				value: "",
				checked: false,
			});
		} catch(e) {
			console.log(e);
			return "";
		}
		return checkBox;
	} else if (rowIdx == 1) {
		// val = msg_id
		var detailsIcon = '<img onclick=\'galaxytool_show_report('+val+')\' src="../images/magnifier2.png" style="cursor: pointer;">';
		return detailsIcon;
	}
	
	var key = store1.getValue(grid1.getItem(rowIdx), "key");
	if (key == "res_sum" || key == "fleet_sum" || key == "def_sum") {
		cell.customClasses.push("sum_row");
	} else if ((key == "metal" || key == "crystal" || key == "deuterium") && val > 0) {
		// use different colors for resources depending on storage capacity
		var size = 0;
		var buildings = store1.getValue(grid1.getItem(37), cell.field);
		if (store1.getValue(grid1.getItem(37), "key") != "h4") console.log("new lines added - adjust report_archive.js!");
		
		if (buildings == "ok") {
			if (galaxytool_is_moon == false) {
				switch(key) {
				case "metal": size = store1.getValue(grid1.getItem(46), cell.field); break;
				case "crystal": size = store1.getValue(grid1.getItem(47), cell.field); break;
				case "deuterium": size = store1.getValue(grid1.getItem(48), cell.field); break;
				}
				if (store1.getValue(grid1.getItem(46), "key") != "mesp") console.log("new lines added - adjust report_archive.js!");
			} else {
				// use moon index
				switch(key) {
				case "metal": size = store1.getValue(grid1.getItem(40), cell.field); break;
				case "crystal": size = store1.getValue(grid1.getItem(41), cell.field); break;
				case "deuterium": size = store1.getValue(grid1.getItem(42), cell.field); break;
				}
				if (store1.getValue(grid1.getItem(40), "key") != "mesp") console.log("new lines added - adjust report_archive.js!");
			}
		}
		
		if (buildings == "ok" || galaxytool_is_moon == true) {
			var capacity = galaxytool.report_display.get_storage_capacity(parseInt(size));
			var stored = parseInt(val);
			
			if (capacity <= stored) {
				cell.customClasses.push("traffic_light_red");
				
			} else if (capacity * 0.9 <=  stored) {
				cell.customClasses.push("traffic_light_yellow");
			}
		}
	} else if (key == "h1" || key == "h2" || key == "h3" || key == "h4" || key == "h5") {
		if (val == "ok") {
			var detailsIcon = '<img src="../images/ok.png"">';
		} else {
			var detailsIcon = '<img src="../images/no.png"">';
		}
		return detailsIcon;
	}
	
	if (!isNaN(parseFloat(val)) && isFinite(val)) {
		// value is numeric
		return NumberFormat(val);
	}

	return val;
}

function galaxytool_archive_fetch_complete(items) {
	if (grid_layout_done == true) {
		return;
	}
	
	var columns = 0;
	var column_name = "";
	do  {
		columns++;
		column_name = "c"+columns;
		var dummy = store1.getValues(items[0],column_name); // start with c1
	}  while ((typeof dummy != "undefined") && dummy != "" && columns < 200);
	
	var fixlayout = {
			noscroll: true,
			cells: [{
				field: 'c0',
				name: 'c0',
				width: '150px',
				formatter: galaxytool_archive_formatter  
			}]
		};	

	var mainlayout = new Array(columns);
	for (var i=1; i<columns; i++) {
		mainlayout[i-1] = {
			field: 'c'+i,
			name: '',
			width: '75px',
			formatter: galaxytool_archive_formatter2
		};
	}
	
	var layout = [fixlayout, mainlayout];  
	
	// set the new layout structure:
	grid_layout_done = true;
	//grid1.setStructure(layout); // triggers fetch_complete too
	grid1.set('structure',layout); // triggers fetch_complete too
}

function galaxytool_archive_init() {
	try {
		dojo.connect(dijit.byId("grid1"), "_onFetchComplete",
				galaxytool_archive_fetch_complete);

	} catch (e) {
		console.log(e);
	}
}

dojo.ready(galaxytool_archive_init);